/**
 * 粒子类
 * @description 单个粒子的属性和行为
 */
class Particle {
    constructor(x, y, color, options = {}) {
        this.x = x;
        this.y = y;
        this.dx = options.dx || (Math.random() - 0.5) * 4;
        this.dy = options.dy || (Math.random() - 0.5) * 4;
        this.life = 1;
        this.color = color;
        this.size = options.size || 3;
    }

    /**
     * 更新粒子状态
     */
    update() {
        this.x += this.dx;
        this.y += this.dy;
        this.life -= 0.02;
    }

    /**
     * 绘制粒子
     * @param {CanvasRenderingContext2D} ctx - Canvas上下文
     */
    draw(ctx) {
        ctx.save();
        ctx.globalAlpha = this.life;
        ctx.fillStyle = this.color;
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
        ctx.fill();
        ctx.restore();
    }

    /**
     * 检查粒子是否已死亡
     * @returns {boolean} 是否已死亡
     */
    isDead() {
        return this.life <= 0;
    }
}

/**
 * 粒子系统类
 * @description 管理所有粒子效果
 */
export class ParticleSystem {
    constructor() {
        this.particles = [];
    }

    /**
     * 创建粒子爆炸效果
     * @param {number} x - X坐标
     * @param {number} y - Y坐标
     * @param {string} color - 粒子颜色
     * @param {number} count - 粒子数量
     * @param {Object} options - 额外选项
     */
    createExplosion(x, y, color, count = 10, options = {}) {
        for (let i = 0; i < count; i++) {
            this.particles.push(new Particle(x, y, color, options));
        }
    }

    /**
     * 创建尾气效果
     * @param {number} x - X坐标
     * @param {number} y - Y坐标
     * @param {string} color - 粒子颜色
     * @param {number} count - 粒子数量
     */
    createExhaust(x, y, color, count = 2) {
        for (let i = 0; i < count; i++) {
            this.particles.push(new Particle(x, y, color, {
                dx: (Math.random() - 0.5) * 3,
                dy: Math.random() * 2,
                size: 2
            }));
        }
    }

    /**
     * 更新所有粒子
     */
    update() {
        for (let i = this.particles.length - 1; i >= 0; i--) {
            const particle = this.particles[i];
            particle.update();

            if (particle.isDead()) {
                this.particles.splice(i, 1);
            }
        }
    }

    /**
     * 绘制所有粒子
     * @param {CanvasRenderingContext2D} ctx - Canvas上下文
     */
    render(ctx) {
        this.particles.forEach(particle => particle.draw(ctx));
    }

    /**
     * 清空所有粒子
     */
    clear() {
        this.particles = [];
    }

    /**
     * 获取粒子数量
     * @returns {number} 当前粒子数量
     */
    getParticleCount() {
        return this.particles.length;
    }
} 